﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using ToolBoxPro;
using LinqObj;
using System.Collections.Generic;
using System.IO;
using System.Web.Mail;

public partial class artwork : RedirectPage
{
    private int campaignID;
    private int propertyID;
    private Property property;
    private int agentGroupID;
    private static string propertyAddress = "";
    private static string approvedFiles = "";
    private static string userFiles = "";
    private static string propertDetails = "";
    private static string vendorDetails = "";

    private Agent_Group group;

    protected void Page_Load(object sender, EventArgs e)
    {
        agentGroupID = Convert.ToInt32(Session[FormContract.AGENT_GROUP_ID]);
        this.group = Agent_Group.GetAgentGroup(agentGroupID);

        if (!IsPostBack)
        {
            ((Label)Master.FindControl("lblTitle")).Text = "Art Work";
            ((System.Web.UI.HtmlControls.HtmlImage)Master.FindControl("imgHeading")).Src = "images/icon_office.gif";
            if (Request.QueryString["property_id"] != null)
            {
                int propID = Convert.ToInt32(Request.QueryString["property_id"]);
                property = Property.GetProperty(propID);
                lblPropName.Text = property.PropertyHeading;
                if (property.address1 != "")
                    divAddress.InnerHtml = property.address1 + "<br />";
                if (property.address2 != "")
                    divAddress.InnerHtml += property.address2 + "<br />";
                if(property.suburb != "")
                    divAddress.InnerHtml += property.suburb + "<br />";
                if (property.country != "")
                    divAddress.InnerHtml += property.country + "<br />";
                if (property.address2.Equals(""))
                    propertyAddress = property.address1;
                else
                    propertyAddress = property.property_id + " " + property.address1 + " " + property.address2 + " " + property.suburb;
                
                propertDetails = propertyAddress + ", " + property.postcode + ", " + property.suburb;
                Agent agent = Agent.GetAgentByAgentID(Convert.ToInt32(property.agent_id));
                vendorDetails = property.Vendor_Detail.VendorDetail;
                lblOfficerName.Text= agent.agent_name;
            }

            if (Directory.Exists(Server.MapPath(Page.ResolveUrl("~/") + group.agent_group_name + "\\" + propertyAddress + "/")) && AllFolderExists())
            {
                divFolder.Visible = true;
                divNoFolder.Visible = false;
                btnSubmit.Visible = true;
                FillGrid();
            }
            else
            {
                divFolder.Visible = false;
                divNoFolder.Visible = true;
                btnSubmit.Visible = false;
            }
            approvedFiles = "";
            userFiles = "";
        }

    }
    public bool AllFolderExists()
    {
        string dPath = Server.MapPath(Page.ResolveUrl("~/") + group.agent_group_name + "\\" + propertyAddress + "/Waiting for approval/");
        string aPath = Server.MapPath(Page.ResolveUrl("~/") + group.agent_group_name + "\\" + propertyAddress + "/approved/");
        if (Directory.Exists(dPath + "floor plan") && Directory.Exists(dPath + "photos") && Directory.Exists(dPath + "copy writing")
            && Directory.Exists(dPath + "floor plan") && Directory.Exists(dPath + "brochures") && Directory.Exists(dPath + "misc")
            && Directory.Exists(aPath + "board") && Directory.Exists(aPath + "photos") && Directory.Exists(aPath + "copy writing")
            && Directory.Exists(aPath + "board") && Directory.Exists(aPath + "brochures") && Directory.Exists(aPath + "misc"))
            return true;
        else
            return false;
    }
    private void FillGrid()
    {
        DataTable dtFolder = new DataTable();
        dtFolder.Columns.Add("FolderName");
        DataRow dr = AddFolder(dtFolder.NewRow(), "Floor Plan");
        dtFolder.Rows.Add(dr);
        dr = AddFolder(dtFolder.NewRow(), "Photos");
        dtFolder.Rows.Add(dr);
        dr = AddFolder(dtFolder.NewRow(), "Copy Writing");
        dtFolder.Rows.Add(dr);
        dr = AddFolder(dtFolder.NewRow(), "Board");
        dtFolder.Rows.Add(dr);
        dr = AddFolder(dtFolder.NewRow(), "Brochures");
        dtFolder.Rows.Add(dr);
        dr = AddFolder(dtFolder.NewRow(), "Misc");
        dtFolder.Rows.Add(dr);
        dlFolder.DataSource = dtFolder;
        dlFolder.DataBind();
        dlApprovedFolder.DataSource = dtFolder;
        dlApprovedFolder.DataBind();

    }

    private DataRow AddFolder(DataRow dr, string folderName)
    {
        dr["FolderName"] = folderName;
        return dr;
    }

    protected void dlFile_ItemCommand(object sender, DataListCommandEventArgs e)
    {
        System.Threading.Thread.Sleep(500);
        if (e.CommandName == "Approve")
        {
            string fileName = e.CommandArgument.ToString();
            ApproveFile(fileName);
            FillGrid();
            string script = "";
            script = "<script>";
            script += "alert('File has been approved successfully');";
            //script += "window.location.hash=\"DETAILS\";";
            script += "</script>";
            ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", script, false);
        }
        if (e.CommandName == "Download")
        {
            string fileName = e.CommandArgument.ToString();
            DownloadFile(fileName);
        }
        if (e.CommandName == "Disapprove")
        {
            string fileName = e.CommandArgument.ToString();
            DisApproveFile(fileName);
            FillGrid();
            string script = "";
            script = "<script>";
            script += "alert('File has been disapproved successfully');";
            //script += "window.location.hash=\"floor plan\";";
            script += "</script>";
            ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", script, false);
        }

    }
    private void ApproveFile(string fileName)
    {
        string approvedPath = fileName.ToLower().Replace("waiting for approval", "Approved");
        string nonApprovePath = fileName;

        FileInfo fileApprove = new FileInfo(nonApprovePath);
        if (File.Exists(approvedPath))
        {
            File.Delete(approvedPath);
        }
        fileApprove.MoveTo(approvedPath);
        //approvedFiles += fileApprove.Name + ",";
        string[] folder = fileName.Split('\\');

        approvedFiles += Page.ResolveUrl("~/") + group.agent_group_name + "\\" + propertyAddress + "/Approved/" + folder[folder.Length - 2].ToString() + "/" + fileApprove.Name + ",";
        userFiles += fileApprove.Name + ",";
    }
    private void DisApproveFile(string fileName)
    {
        string approvedPath = fileName;
        string nonApprovePath = fileName.ToLower().Replace("approved", "waiting for approval");

        FileInfo fileApprove = new FileInfo(approvedPath);
        if (File.Exists(nonApprovePath))
        {
            File.Delete(nonApprovePath);
        }
        fileApprove.MoveTo(nonApprovePath);
        //approvedFiles += fileApprove.Name + ",";
        //disapprovedFiles += nonApprovePath.Substring(nonApprovePath.IndexOf("/"), nonApprovePath.Length - nonApprovePath.IndexOf("/")) + ",";
        //string[] folder = fileName.Split('/');
        //disapprovedFiles += Page.ResolveUrl("~/") + "Office\\" + propertyAddress + "/Waiting for approval/" + folder[folder.Length - 1].ToString() + "/" + fileApprove.Name + ",";
    }

    //private void InsertIntoDB()
    //{
    //    SqlConnection objCon = new SqlConnection();
    //}

    private void DownloadFile(string fileName)
    {
        FileInfo fileInfo = new FileInfo(fileName);
        Response.Buffer = true;
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name.Replace(" ", "_"));
        Response.WriteFile(fileName);
        Response.Flush();
        Response.Close();
        Response.End();
    }

    protected void dlFolder_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        DataList dlFile = new DataList();
        dlFile = (DataList)e.Item.FindControl("dlFile");
        Label lblFolderName = new Label();
        lblFolderName = (Label)e.Item.FindControl("lblFolderName");
        DataTable dtFiles = new DataTable();
        dtFiles.Columns.Add("FilePath");
        dtFiles.Columns.Add("FolderName");
        HtmlGenericControl divMsg = new HtmlGenericControl();
        divMsg = (HtmlGenericControl)e.Item.FindControl("divMsg");
        HtmlGenericControl divScroll = new HtmlGenericControl();
        divScroll = (HtmlGenericControl)e.Item.FindControl("divScroll");
        HtmlGenericControl divScroll2 = new HtmlGenericControl();
        divScroll2 = (HtmlGenericControl)e.Item.FindControl("divScroll2");
        if (dlFile != null && lblFolderName != null)
        {
            if (Directory.Exists(Server.MapPath(Page.ResolveUrl("~/") + group.agent_group_name + "\\" + propertyAddress + "/Waiting for approval/" + lblFolderName.Text)))
            {
                divFolder.Visible = true;
                divNoFolder.Visible = false;
                btnSubmit.Visible = true;
                string[] fileName = Directory.GetFiles(Server.MapPath(Page.ResolveUrl("~/") + group.agent_group_name + "\\" + propertyAddress + "/Waiting for approval/" + lblFolderName.Text));

                for (int i = 0; i < fileName.Length; i++)
                {
                    DataRow dr = dtFiles.NewRow();
                    dr["FilePath"] = fileName[i].ToString();
                    dr["FolderName"] = lblFolderName.Text;
                    dtFiles.Rows.Add(dr);
                }
            }
            else
            {
                divFolder.Visible = false;
                divNoFolder.Visible = true;
                btnSubmit.Visible = false;
            }
        }
        dlFile.DataSource = dtFiles;
        dlFile.DataBind();

        if (dtFiles.Rows.Count <= 9)
        {
            divScroll2.Attributes.Add("width", "720px");
            divScroll.Attributes.Add("class", "");
        }
        else
        {
            int width = 760 + (100 * (dtFiles.Rows.Count - 9));
            divScroll2.Attributes.Add("width", width + "px");
            divScroll.Attributes.Add("class", "scroll");
        }

        if (dtFiles.Rows.Count <= 0)
        {
            divMsg.Visible = true;
            divScroll.Visible = false;
        }
        else
        {
            divMsg.Visible = false;
            divScroll.Visible = true;
        }
    }

    protected void dlFile_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        HtmlGenericControl divFile = new HtmlGenericControl();
        divFile = (HtmlGenericControl)e.Item.FindControl("divFile");
        
        Label lblFileName = new Label();
        lblFileName = (Label)e.Item.FindControl("lblFileName");
        Label lblFolderName = new Label();
        lblFolderName = (Label)e.Item.FindControl("lblFolderName");

        ImageButton btnDownload = new ImageButton();
        btnDownload = (ImageButton)e.Item.FindControl("btnDownload");
        if (btnDownload != null)
            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(btnDownload);

        if (divFile != null && lblFileName != null)
        {
            if (lblFileName.Text.ToLower().Contains("jpg") || lblFileName.Text.Contains("jpe") || lblFileName.Text.Contains("jfif")
                 || lblFileName.Text.Contains("jpeg") || lblFileName.Text.Contains("gif") || lblFileName.Text.Contains("png")
                 || lblFileName.Text.Contains("bmp") || lblFileName.Text.Contains("tif"))
            {
                FileInfo fileInfo = new FileInfo(lblFileName.Text);
                string imgSrc = Page.ResolveUrl("~/") + group.agent_group_name + "/" + propertyAddress + "/Waiting for approval/" + lblFolderName.Text + "/" + fileInfo.Name;
                divFile.InnerHtml = "<a href='" + imgSrc + "' rel='shadowbox'><img src='" + imgSrc + "'/>";
            }
            else if (lblFileName.Text.ToLower().Contains("pdf"))
                divFile.InnerHtml = "<img src='" + Page.ResolveUrl("~/") + "images/pdf.jpg' />";
            else if (lblFileName.Text.ToLower().Contains("txt"))
                divFile.InnerHtml = "<img src='" + Page.ResolveUrl("~/") + "images/img10.jpg' />";
            else if (lblFileName.Text.ToLower().Contains("doc"))
                divFile.InnerHtml = "<img src='" + Page.ResolveUrl("~/") + "images/docx.jpg' />";
            else
                divFile.InnerHtml = "<img src='" + Page.ResolveUrl("~/") + "images/img10.jpg' />";
        }
        ImageButton btnApprove = (ImageButton)e.Item.FindControl("btnApprove");
        if (btnApprove != null)
            btnApprove.Attributes.Add("onclick", "javascript:return " +
                 "confirm('Are you sure you want to approve this file?')");
        
    }

    //approved files
    protected void dlApprovedFolder_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        DataList dlFile = new DataList();
        dlFile = (DataList)e.Item.FindControl("dlApprovedFile");
        Label lblFolderName = new Label();
        lblFolderName = (Label)e.Item.FindControl("lblFolderName");
        DataTable dtFiles = new DataTable();
        dtFiles.Columns.Add("FilePath");
        dtFiles.Columns.Add("FolderName");
        HtmlGenericControl divMsg = new HtmlGenericControl();
        divMsg = (HtmlGenericControl)e.Item.FindControl("divMsg");
        HtmlGenericControl divScroll = new HtmlGenericControl();
        divScroll = (HtmlGenericControl)e.Item.FindControl("divScroll");
        HtmlGenericControl divScroll2 = new HtmlGenericControl();
        divScroll2 = (HtmlGenericControl)e.Item.FindControl("divScroll2");
        if (dlFile != null && lblFolderName != null)
        {
            if (Directory.Exists(Server.MapPath(Page.ResolveUrl("~/") + group.agent_group_name + "\\" + propertyAddress + "/Approved/" + lblFolderName.Text)))
            {
                divFolder.Visible = true;
                divNoFolder.Visible = false;
                btnSubmit.Visible = true;
                string[] fileName = Directory.GetFiles(Server.MapPath(Page.ResolveUrl("~/") + group.agent_group_name + "\\" + propertyAddress + "/Approved/" + lblFolderName.Text));

                for (int i = 0; i < fileName.Length; i++)
                {
                    DataRow dr = dtFiles.NewRow();
                    dr["FilePath"] = fileName[i].ToString();
                    dr["FolderName"] = lblFolderName.Text;
                    dtFiles.Rows.Add(dr);
                }
            }
            else
            {
                divFolder.Visible = false;
                divNoFolder.Visible = true;
                btnSubmit.Visible = false;
            }
        }
        dlFile.DataSource = dtFiles;
        dlFile.DataBind();

        if (dtFiles.Rows.Count <= 9)
        {
            divScroll2.Attributes.Add("width", "720px");
            divScroll.Attributes.Add("class", "");
        }
        else
        {
            int width = 760 + (100 * (dtFiles.Rows.Count - 9));
            divScroll2.Attributes.Add("width", width + "px");
            divScroll.Attributes.Add("class", "scroll");
        }

        if (dtFiles.Rows.Count <= 0)
        {
            divMsg.Visible = true;
            divScroll.Visible = false;
        }
        else
        {
            divMsg.Visible = false;
            divScroll.Visible = true;
        }
    }

    protected void dlApprovedFile_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        HtmlGenericControl divFile = new HtmlGenericControl();
        divFile = (HtmlGenericControl)e.Item.FindControl("divFile");
        HtmlGenericControl divDisapprove = new HtmlGenericControl();
        divDisapprove = (HtmlGenericControl)e.Item.FindControl("divDisapprove");
         Toolbox_User _user = (Toolbox_User)Session[FormContract.USER];
         if (_user.user_name == "aaron_iplan3d")
            divDisapprove.Visible = true;
        else
            divDisapprove.Visible = false;
        Label lblFileName = new Label();
        lblFileName = (Label)e.Item.FindControl("lblFileName");
        Label lblFolderName = new Label();
        lblFolderName = (Label)e.Item.FindControl("lblFolderName");

        ImageButton btnDownload = new ImageButton();
        btnDownload = (ImageButton)e.Item.FindControl("btnDownload");
        if (btnDownload != null)
            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(btnDownload);

        if (divFile != null && lblFileName != null)
        {
            if (lblFileName.Text.ToLower().Contains("jpg") || lblFileName.Text.Contains("jpe") || lblFileName.Text.Contains("jfif")
                 || lblFileName.Text.Contains("jpeg") || lblFileName.Text.Contains("gif") || lblFileName.Text.Contains("png")
                 || lblFileName.Text.Contains("bmp") || lblFileName.Text.Contains("tif"))
            {
                //FileInfo fileInfo = new FileInfo(lblFileName.Text);
                //divFile.InnerHtml = "<img src='" + Page.ResolveUrl("~/") + group.agent_group_name + "/" + propertyAddress + "/Approved/" + lblFolderName.Text + "/" + fileInfo.Name + "' />";
                FileInfo fileInfo = new FileInfo(lblFileName.Text);
                string imgSrc = Page.ResolveUrl("~/") + group.agent_group_name + "/" + propertyAddress + "/Approved/" + lblFolderName.Text + "/" + fileInfo.Name;
                divFile.InnerHtml = "<a href='" + imgSrc + "' rel='shadowbox'><img src='" + imgSrc + "'/>";
            
            }
            else if (lblFileName.Text.ToLower().Contains("pdf"))
                divFile.InnerHtml = "<img src='" + Page.ResolveUrl("~/") + "images/pdf.jpg' />";
            else if (lblFileName.Text.ToLower().Contains("txt"))
                divFile.InnerHtml = "<img src='" + Page.ResolveUrl("~/") + "images/img10.jpg' />";
            else if (lblFileName.Text.ToLower().Contains("doc"))
                divFile.InnerHtml = "<img src='" + Page.ResolveUrl("~/") + "images/docx.jpg' />";
            else
                divFile.InnerHtml = "<img src='" + Page.ResolveUrl("~/") + "images/img10.jpg' />";
        }
        ImageButton btnDisApprove = (ImageButton)e.Item.FindControl("btnDisApprove");
        if (btnDisApprove != null)
            btnDisApprove.Attributes.Add("onclick", "javascript:return " +
                 "confirm('Are you sure you want to disapprove this file?')");
    }

    protected void btnBack_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("propertylist.aspx");
    }

    protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        string approvedfiles = "";
        string userfile = "";
        string body = "";
        string[] approvefiles = approvedFiles.Split(',');
        string[] userfiles = userFiles.Split(',');
        for (int i = 0; i < approvefiles.Length - 1; i++)
        {
            approvedfiles += approvefiles[i].Replace("\\", "/") + "<br /><br />";
            userfile += userfiles[i].Replace("\\", "/") + "<br /><br />";
        }

        body += "<b>Property Details </b><br/>";
        body += propertDetails;
        body += "<br/><br/>";
        body += "<b>Vendor Details </b><br/>";
        body += vendorDetails;
        body += "<br/><br/>";


        string approveMessage = "";
        Toolbox_User _user = (Toolbox_User)Session[FormContract.USER];
        
        //email to admin
        if (!approvedfiles.Trim().Equals(""))
            approveMessage = "<b>Following files has been approved by " + _user.user_name + "</b><br /><br />";

        Notifications emailAdmin = new Notifications("aaronb@iplan3d.com.au", "iplan3d - Artwork approved files", body + approveMessage + approvedfiles);
        //Notifications emailAdmin = new Notifications("kaushal.gajjar@datatechmedia.com", "iplan3d - Artwork approved files", body + approveMessage + approvedfiles);
        
        emailAdmin.SendEmail();

        //email to user
        if (!userfile.Trim().Equals(""))
            approveMessage = "<b>You have approved following files </b><br /><br />";
        
        Notifications emailUser = new Notifications(_user.Email, "iplan3d - Artwork approved files",body+ approveMessage + userfile);
        //Notifications emailUser = new Notifications("kaushal.gajjar@datatechmedia.com", "iplan3d - Artwork approved files", body + approveMessage + userfile);

        emailUser.SendEmail();
        Response.Redirect("propertylist.aspx");
    }

    private void SendMail(string from, string to, string subject, string body)
    {
        System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
        string mailfrom = from;
        string mailhost = mailfrom.Substring(0, mailfrom.IndexOf("@"));
        mailfrom = mailhost + "@seorank.com.au";
        mail.To = to;
        mail.Subject = subject;
        mail.From = mailfrom;
        mail.BodyFormat = MailFormat.Html;
        mail.Body = body;
        mail.Headers.Add("Reply-To", from);
        SmtpMail.Send(mail);
    }
}
